
#import "FAMCameraTakeShotViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
@interface FAMCameraTakeShotViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,AVCapturePhotoCaptureDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *FAMPhotoImageView;
@property (weak, nonatomic) IBOutlet UIView *FAMPhotographBackView;


@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCapturePhotoOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;

@end

@implementation FAMCameraTakeShotViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self FAM_showUi];
    
}
- (void)FAM_showUi{
    self.title = @"Take a shot";
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.backgroundColor = kCustom0xColor(0x191919, 1.0);
    rightButton.layer.cornerRadius = 15;
    rightButton.clipsToBounds = YES;
    rightButton.titleLabel.font = [UIFont systemFontOfSize:12];
    rightButton.layer.masksToBounds = YES;
    [rightButton setTitle:@"Stencil" forState:UIControlStateNormal];
    [rightButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [rightButton setImage:[UIImage imageNamed:@"camera_camera"] forState:UIControlStateNormal];
    rightButton.frame = CGRectMake(0, 0, 84, 30);
    [rightButton addTarget:self action:@selector(FAM_rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
    [self FAM_getFirstPhoto];
    [self FAM_initAVCaptureSession];
}
- (void)FAM_getFirstPhoto{
    WeakSelf(self);
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status != PHAuthorizationStatusNotDetermined) {
            if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf FAM_hintMessage];
                });
            }else{
                __block PHAsset *firstPhoto = nil;
                PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
                [smartAlbums enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
                    fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
                    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:fetchOptions];
                    if (assetsFetchResults.count > 0) {
                        firstPhoto = assetsFetchResults.lastObject;
                        *stop = YES;
                    }
                }];
                
                if (firstPhoto) {
                    [[PHImageManager defaultManager] requestImageForAsset:firstPhoto targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage *image, NSDictionary *info) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            weakSelf.FAMPhotoImageView.image = image;
                        });
                    }];
                }
            }
        }
    }];
}
- (void)FAM_initAVCaptureSession{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied){
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"reminder" message:@"Whether to enable camera permissions" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"ok" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
            }
        }];
        [alertC addAction:alertA];
        [self presentViewController:alertC animated:YES completion:nil];
        return;
    }
    self.session = [[AVCaptureSession alloc]init];
    NSError *error;
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (self.device == nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"reminder" message:@"The device does not have a camera" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    self.session.sessionPreset = AVCaptureSessionPresetPhoto;
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    self.output = [[AVCapturePhotoOutput alloc] init];
    NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
    AVCapturePhotoSettings * photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
    photoSettings.autoStillImageStabilizationEnabled = YES;
    photoSettings.highResolutionPhotoEnabled = YES;
    photoSettings.flashMode = AVCaptureFlashModeAuto;
    [self.output setPhotoSettingsForSceneMonitoring:photoSettings];
    if ([self.session canAddOutput:self.output]) {
        [self.session addOutput:self.output];
    }
    [self.output.connections.lastObject setVideoOrientation:AVCaptureVideoOrientationPortrait];
    
    self.preview = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    [self.preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [self.FAMPhotographBackView.layer addSublayer:self.preview];
    self.preview.frame = CGRectMake(0, 0, SCREEN_WIDTH - 30, SCREEN_HEIGHT);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self.session startRunning];
    });
}
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
    NSData *data = [photo fileDataRepresentation];
    UIImage *image = [UIImage imageWithData:data];
    FAMCameraConfirmPhotoViewController *vc = [[FAMCameraConfirmPhotoViewController alloc]init];
    vc.FAMSelectedImage = image;
    vc.FAMCateType = self.FAMCateType;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)FAM_rightButtonClick:(UIButton *)sender{
    [self.navigationController pushViewController:[FAMCameraStencilViewController new] animated:YES];
}
- (IBAction)FAM_photographButtonClick:(UIButton *)sender {
    [sender setUserInteractionEnabled:NO];
    AVCapturePhotoSettings *set = [AVCapturePhotoSettings photoSettings];
    [self.output capturePhotoWithSettings:set delegate:self];
    [self performSelector:@selector(FAM_setButtonUserInteractionEnabled:) withObject:sender afterDelay:1.5];
}
- (void)FAM_setButtonUserInteractionEnabled:(UIButton *)sender {
    [sender setUserInteractionEnabled:YES];
}
- (IBAction)FAM_photoAlbumButtonClick:(UIButton *)sender {
    if ([self FAM_isPhotoLibraryAvailable]) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
        [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }else{
        [self FAM_hintMessage];
    }
}
- (BOOL)FAM_isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (void)FAM_hintMessage{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"reminder" message: @"Whether to enable the permission of the album" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];

    UIAlertAction *action = [UIAlertAction actionWithTitle:@"ok" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        }
    }];
    UIAlertAction *actionS = [UIAlertAction actionWithTitle:@"cancel" style: UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];
    [alertController addAction:action];
    [alertController addAction:actionS];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    [self dismissViewControllerAnimated:YES completion:^{
        FAMCameraConfirmPhotoViewController *vc = [[FAMCameraConfirmPhotoViewController alloc]init];
        vc.FAMSelectedImage = info[UIImagePickerControllerOriginalImage];
        vc.FAMCateType = self.FAMCateType;
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

@end
